﻿using System.Reflection;
using System.Web.Mvc;
using Web7.Core.Security;

namespace Web7.Core.Attribute
{
    public class FormValueVerifyAttribute : ActionMethodSelectorAttribute
    {
        private readonly string _submitButtonName;
        private readonly Permission Permission;

        public IAuthorizer Authorizer
        {
            get { return DependencyResolver.Current.GetService<IAuthorizer>(); }
        }

        public IPermission PermissionProviderService
        {
            get { return DependencyResolver.Current.GetService<IPermission>(); }
        }

        public FormValueVerifyAttribute(string submitButtonName, Permission permission)
        {
            _submitButtonName = submitButtonName;
            Permission = permission;
        }

        public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
        {
            var value = controllerContext.HttpContext.Request.Form[_submitButtonName];

            return !string.IsNullOrEmpty(value) && Authorizer.Authorize(Permission);
        }
    }
}
